#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "common.h"
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>

bool Makefifo()
{
    int n = mkfifo(FILENAME,0666);
    if(n < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }

    std::cout << "mkfifo success... read" << std::endl;
    return true;
}


int main()
{
Start:
    // 1.创建命名管道
    int rfd = open(FILENAME, O_RDONLY);
    if (rfd == -1)
    {
        std::cerr << "errno:" << errno << ",strerrormessage:" << strerror(errno) << std::endl;
        if(Makefifo())
        {
            goto Start;
        }
        else 
        {
            return 1;
        }
    }
    char buffer[1024];
    while (true)
    {
        std::cout << "Read start......" << std::endl;
        int n = read(rfd,buffer,sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "Client say# " << buffer << std::endl;
        }
        else if( n == 0)
        {
            std::cout << "client quit, server quit too!" << std::endl;
            break;
        }
    }

    close(rfd);
    std::cout << "close fifo success..." << std::endl;


    return 0;
}